<!--
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-07-18 09:37:29
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-07-26 15:23:50
 * @FilePath: \HuiLin\pages\homePages\repairService.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view style="min-height: 100vh;">
		<headerSlot :propsColor="propsColor">
			<template v-slot:header>
				<view class="header_slot flex justify-start align-center" @click="closePage()">
					<view class="action back-btn">
						<text class="cuIcon-back "></text>
					</view>
					<view class="content text-bold">
						家庭维修
					</view>
				</view>
			</template>
		</headerSlot>
		<view class="form_box">
			<uni-forms :modelValue="formData" :rules="rulesForm" ref="form" validate-trigger="submit">
				<uni-section title="服务信息" type="line" titleFontSize='16px'></uni-section>
				<uni-forms-item label="服务类型" name="type">
					<uni-data-select v-model="formData.type" :clear="false" @change="selectType"
						:localdata="serviceTypes"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="服务时间" name="dateTime">
					<uni-datetime-picker type="datetime" v-model="formData.dateTime" />
				</uni-forms-item>
				<uni-forms-item label="服务地址" name="address">
					<view class="flex align-center">
						<uni-easyinput type="text" v-model="formData.address" placeholder="请输入服务地址" style="flex:1"
							readonly />
						<button class="choose-addr-btn" @click="chooseAddress">选择地址</button>
					</view>
				</uni-forms-item>
				<uni-forms-item label="备注" name="remark">
					<uni-easyinput type="textarea" v-model="formData.remark" placeholder="可填写特殊需求" autoHeight />
				</uni-forms-item>
			</uni-forms>
			<view class="info-section">
				<view class="price-row">
					<text class="label">服务价格：</text>
					<text class="price">￥{{ price }}</text>
				</view>
				<view class="desc-row">
					<text class="label">服务说明：</text>
					<text class="desc">{{ serviceDesc }}</text>
				</view>
			</view>
			<view class="release_btn">
				<button class="service-btn main" @click="onSubmit">提交预约</button>
				<button class="service-btn outline" @click="goHistory">历史订单</button>
			</view>
		</view>
	</view>
</template>

<script>
	import headerSlot from '@/components/header-slot.vue';
	import {
		getRepairServiceTypes
	} from '@/api/order.js';
	import RepairServicePayment from '@/utils/RepairServicePayment.js';
	import storage from '@/utils/storage.js';
	export default {
		name: "RepairService",
		components: {
			headerSlot
		},
		data() {
			return {
				propsColor: '#fff',
				serviceTypes: [], // 动态获取
				userInfo: {}, // 用户信息
				formData: {
					type: '',
					dateTime: '',
					address: '',
					remark: ''
				},
				rulesForm: {
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择服务类型'
						}]
					},
					dateTime: {
						rules: [{
							required: true,
							errorMessage: '请选择服务时间'
						}]
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '请输入服务地址'
						}]
					}
				},
				price: 0,
				serviceDesc: '请选择服务类型',
				loading: false,
				paymentHandler: new RepairServicePayment(),
				isPaying: false
			}
		},
		onLoad() {
			this.userInfo = storage.getUserInfo();
			this.getServiceTypes();
		},
		onReady() {
			this.$refs.form.setRules(this.rulesForm);
		},
		onShow() {
			const selectedAddr = uni.getStorageSync('selectedAddress').fullAddress;
			if (selectedAddr) {
				this.formData.address = selectedAddr;
				uni.removeStorageSync('selectedAddress');
			}
		},
		onUnload() {
			// 页面卸载时停止所有轮询
			if (this.paymentHandler) {
				this.paymentHandler.stopAllPolling();
			}
		},
		methods: {
			async getServiceTypes() {
				this.loading = true;
				try {
					// 获取用户绑定的小区ID
					const communityId = this.userInfo.community && this.userInfo.community._id;
					
					const res = await getRepairServiceTypes('repair', communityId);
					if (res.data.code === 200) {
						this.serviceTypes = Array.isArray(res.data && res.data.data) ?
							res.data.data.map(item => ({
								value: item._id,
								text: item.name,
								price: item.price,
								desc: item.desc
							})) : [];
						if (!this.serviceTypes.length) {
							this.price = 0;
							this.serviceDesc = '当前服务未开通'
						}
					} else {
						uni.showToast({
							title: res.data.message || '获取服务类型失败',
							icon: 'none'
						});
					}
				} catch (e) {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			selectType(e) {
				console.log(e);
				let arr = this.serviceTypes.filter(item => item.value === e)
				if (arr.length > 0) {
					this.price = arr[0].price
					this.serviceDesc = arr[0].desc
				}
			},
			closePage() {
				uni.navigateBack();
			},
			chooseAddress() {
				this.$router.smartNavigate({
					url: '/pages/mePages/address/addressManagement?select=1'
				});
			},
			onSubmit() {
				this.$refs.form.validate().then(async valid => {
					if (valid) {
						if (this.isPaying) {
							uni.showToast({
								title: '正在处理中，请稍候',
								icon: 'none'
							});
							return;
						}

						this.isPaying = true;
						uni.showLoading({
							mask: true,
							title: '创建订单中...'
						});

						try {
							const orderData = {
								typeId: this.formData.type,
								dateTime: this.formData.dateTime,
								address: this.formData.address,
								remark: this.formData.remark
							};

							// 使用支付处理器处理完整支付流程
							await this.paymentHandler.processPayment(
								orderData,
								// 支付成功回调
								(orderId, result) => {
									uni.hideLoading();
									uni.showToast({
										title: '预约成功，支付完成！',
										icon: 'success'
									});

									// 重置表单
									this.resetForm();

									// 跳转到历史订单页面
									setTimeout(() => {
										uni.redirectTo({
											url: '/pages/homePages/repairOrderHistory'
										});
									}, 1500);
								},
								// 支付失败回调
								(orderId, error) => {
									uni.hideLoading();
									uni.showToast({
										title: error.message || '支付失败',
										icon: 'none'
									});
								},
								// 支付超时回调
								(orderId) => {
									uni.hideLoading();
									uni.showToast({
										title: '支付状态查询超时，请稍后手动检查',
										icon: 'none'
									});
								}
							);

						} catch (error) {
							uni.hideLoading();
							uni.showToast({
								title: error.message || '创建订单失败',
								icon: 'none'
							});
						} finally {
							this.isPaying = false;
						}
					}
				}).catch(() => {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					});
				});
			},
			resetForm() {
				this.formData = {
					type: '',
					dateTime: '',
					address: '',
					remark: ''
				};
				this.price = 0;
				this.serviceDesc = '请选择服务类型';
			},
			goHistory() {
				this.$router.smartNavigate({
					url: '/pages/homePages/repairOrderHistory'
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	.back-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.form_box {
		position: relative;
		min-height: 80vh;
		margin: 24rpx;
		padding: 24rpx;
		background-color: #fff;
	}

	.release_btn {
		margin-top: 32rpx;
		padding: 0 32rpx;
	}

	.service-btn {

		display: block;
		width: 100%;
		margin-bottom: 24rpx;
		font-size: 32rpx;
		border-radius: 12rpx;
		border: none;
		transition: background 0.2s;
	}

	.service-btn.main {
		background: #fd6e37;
		color: #fff;
		box-shadow: 0 4rpx 16rpx #fd6e3722;
	}

	.service-btn.outline {
		background: #fff;
		color: #fd6e37;
		border: 1px solid #fd6e37;
	}

	.choose-addr-btn {
		margin-left: 16rpx;
		font-size: 26rpx;
		color: #fd6e37;
		background: #fff7f2;
		border: 1px solid #fd6e37;
		border-radius: 8rpx;
		padding: 0 24rpx;
		height: 64rpx;
		line-height: 64rpx;
	}

	.info-section {
		margin: 32rpx 0 24rpx 0;
		padding: 32rpx;
		background: #f9f9f9;
		border-radius: 12rpx;
	}

	.price-row,
	.desc-row {
		display: flex;
		align-items: flex-start;
		margin-bottom: 16rpx;
	}

	.label {
		color: #fd6e37;
		font-weight: 700;
		min-width: 120rpx;
	}

	.price {
		color: #e64340;
		font-size: 36rpx;
		font-weight: 700;
	}

	.desc {
		color: #666;
		font-size: 28rpx;
		flex: 1;
	}
</style>